package org.chy.utils.result;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author  Chenghy
 * @date    2017年12月21日  11时16分03秒
 * @version 1.0
 */
@Aspect
@Component
public class ControllerAop {
	
	private static Logger logger = LoggerFactory.getLogger(ControllerAop.class);
	
	//@Pointcut("execution(* org.chy.controller..*(..)) && @annotation(org.springframework.web.bind.annotation.PostMapping)")
	@Pointcut("execution(* org.chy.controller..*(..))")
	public void controllerMethodPointcut() {}
	
	@Before("controllerMethodPointcut()")
	public void doBeforeAdvice(JoinPoint joinPoint) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		logger.info("---------------------------------------------------------------------------------------");
		logger.info("---------------------------- controller log info --------------------------------------");
		logger.info("url: " + request.getRequestURL().toString());
		logger.info("http-method: " + request.getMethod());
		logger.info("ip: " + request.getRemoteAddr());
		logger.info("class-method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		logger.info("args: " + Arrays.toString(joinPoint.getArgs()));
		logger.info("---------------------------- mapper log info ------------------------------------------");
	}
	
	@Around("controllerMethodPointcut()")
	public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
		ResultBean<?> result ;
		try {
			result = (ResultBean<?>) proceedingJoinPoint.proceed();
		} catch (Throwable e) {
			result = handlerExceptioin(proceedingJoinPoint,e);
		}
		return result;
	}
	
	private ResultBean<?> handlerExceptioin(ProceedingJoinPoint pjp,Throwable e){
		ResultBean<?> resultBean = new ResultBean<>();
		//已知异常
		if (e instanceof RuntimeException) {
			resultBean.setMsg("大胸弟,运行时异常了啊...............");
			resultBean.setCode(ResultBean.FAIL);
		}else if (e instanceof NullPointerException) {
			resultBean.setMsg("大胸弟,空指针异常了啊...............");
			resultBean.setCode(ResultBean.FAIL);
		} else if (e instanceof Exception) {
			resultBean.setMsg(e.getLocalizedMessage());
			resultBean.setCode(ResultBean.FAIL);
		} else {
			resultBean.setMsg(e.toString());
			resultBean.setCode(ResultBean.FAIL);
		}
		return resultBean;
	}
}	